package com.xingda.packing.dmss.task.generate;

import com.xingda.packing.dmss.domain.CacheLocation;
import com.xingda.packing.dmss.domain.PackProductionLine;
import com.xingda.packing.dmss.domain.Wheel;
import com.xingda.packing.dmss.enums.AlarmTriggerType;
import com.xingda.packing.dmss.enums.TaskState;
import com.xingda.packing.dmss.enums.WheelType;
import com.xingda.packing.dmss.task.ticket.AbstractTaskTicket;
import com.xingda.packing.dmss.task.ticket.StorageTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 抓取位放缓存位
 *
 * @author LEGION
 */
@Order(4)
@Component
@Slf4j
public class StorageGenerate implements TaskGenerateService {
    @Override
    public AbstractTaskTicket generate(PackProductionLine productionLine, int area) {
        if (!productionLine.getRobot().checkCanAssignTaskTicket(area)) {
            return null;
        }
        if (!productionLine.getRobot().canAssignTask(area)) {
            return null;
        }
        if (productionLine.getRobot().isEmpty(area)) {
            return null;
        }
        if (!productionLine.getRobot().checkActionStatus(area)) {
            productionLine.getRobot().createAlarmEvent("当前区域存在未完成任务,已停止机器人,请去后台管理页面:[操作管理-动作操作]查看", area);
            productionLine.setInitRunning(area, false);
            return null;
        }
        //缓存位初始化
        productionLine.getCacheArea().getLocationList(area).clear();
        productionLine.getCacheArea().initStatus(area);
        Wheel wheel = productionLine.getRobot().getWheel(area);
        //缓存位满报警
        if (productionLine.getCacheArea().isFull(area)) {
            productionLine.getRobot().createAlarmEvent("缓存位已到警戒值！已停止系统", area);
            productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.CACHE_FULL, true, area);
            productionLine.setInitRunning(area, false);
            return null;
        } else {
            productionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.CACHE_FULL, false, area);
        }
        Optional<CacheLocation> cacheLocation = productionLine.getCacheArea().nextPutLocationNo(WheelType.getByTypeName(wheel.getVFree2()).getType(), area);
        if (!cacheLocation.isPresent()) {
            log.error("区域{}->缓存位已满", area);
            return null;
        }
        StorageTicket ticket = new StorageTicket();
        ticket.setState(TaskState.NEW);
        ticket.setCacheLocationNo(cacheLocation.get().getNo());
        ticket.setWheel(wheel);
        productionLine.getRobot().createStorageEvent(ticket, area);
        return ticket;
    }
}
